Treating a String as an Array

Sometimes it is easier to store information in strings rather than arrays. This saves lines of code and increases maintainability. This example shows one way to store month names in a string and index them.

Month
Number:



Discussion

Reuse this routine for any data-collection strings. This routine may be somewhat awkward, but it collapses data information into a compact, convenient representation and uses a minimum of extra memory.
// Month string
var months = "January:February:March:April:May:June:July:"+
        "August:September:October:November:December:"

// Find the substring at index n, counting 0 to n
function doIndex(aString, n)
{
    
    var str=""+aString
    
    // Count until the correct index
    for(var i = 0; i < n; i++)
    {
        var where = str.indexOf(':', 1)
        str = str.substring(where+1, str.length)
    }

    // Lop off the end of the string
    return str.substring(0, str.indexOf(':'))
}

function choose()
{
    document.forms[0].month.value=
        doIndex(months, document.forms[0].input.options.selectedIndex)
}
Copyright ©1998 by Charles River Media, All Rights Reserved